package com.yl.nettylearning.netty.day01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author yangl
 */
public class Client {
    public static void main(String[] args) throws Exception{
        EventLoopGroup eventExecutors = new NioEventLoopGroup();
        //创建客户端启动对象
        //客户端使用的是BootStrap，服务端用的是ServerBootStrap
        Bootstrap bootstrap = new Bootstrap();
        //设置相关参数
        try {
            bootstrap.group(eventExecutors) //设置线程
                    .channel(NioSocketChannel.class) //设置客户端通道的实现类（反射）
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ClientHandler());    //加入自己的处理器
                        }
                    });
            System.out.println("=======客户端 is ready=====");
            //启动客户端，连接服务器端
            //ChannelFuture 涉及到netty的异步原型
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
            //监听关闭通道 sync:非阻塞
            channelFuture.channel().closeFuture().sync();
        }finally {
            //出现异常，关闭通道
            eventExecutors.shutdownGracefully();
        }
    }
}
